#region Microsoft Public License
/*
 * (c) Copyright Chenjun Wu. http://utablesdk.codeplex.com
 * 
 * This source is subject to the Microsoft Public License (Ms-PL).
 * Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
 * All other rights reserved.
 */
#endregion

﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using UTable.Objects.Controls;
using UTable.Objects.Policies;
using UTable.ObjectManager.Commands;
using System.IO;
using System.Security.Permissions;
using System.Security;
using System.Windows.Threading;
using UTable.Logger;
using UTable.Input.MultiTouch;

namespace UTable.Objects
{
    /// <summary>
    /// Interaction logic for UWorkspaceContent.xaml
    /// </summary>
    public partial class UWorkspace : UObject, IControlDisposable
    {
        public UWorkspace()
        {
            // this.OperatingState = ObjectOperatingState.Viewing;
            InitializeComponent();
            this.DataContext = this;

            PhysicalLayoutPolicyParameter parameter = new PhysicalLayoutPolicyParameter(false, 0.7d, 0.1d);
            this.LayoutPolicyParameter = parameter;
            this.LayoutPolicyType = typeof(PhysicalLayoutPolicy);

            this.DrawerGrid.ItemDropOut += new UGridViewEventHandler(DrawerGrid_ItemDropOut);
			this.DrawerGrid.ItemTapped += new UGridViewEventHandler(DrawerGrid_ItemTapped);
            this.ChildrenChanged += new ObjectChildrenChangedEventHandler(UWorkspace_ChildrenChanged);
			this.Activated += new EventHandler(UWorkspace_Activated);
			this.Unactivated += new EventHandler(UWorkspace_Unactivated);
			ReadRegionBorder.InputReceived += new UTable.Input.InputEventHandler(ReadRegionBorder_InputReceived);

			RefreshLibrary();
			RefreshControlButtons();
            this.Loaded += new RoutedEventHandler(UWorkspace_Loaded);
		}

        void UWorkspace_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (UObjectPreview obj in this.DrawerGrid.Items)
            {
                obj.Menu.Loaded += new RoutedEventHandler(Menu_Loaded);
            }
        }

        void Menu_Loaded(object sender, RoutedEventArgs e)
        {
            UElementMenu menu = sender as UElementMenu;
            menu.Tag = this.Number;

            int i = 0;
            for (; i < menu.Items.Count; i++)
            {
                if ((menu.Items[i] as UElementMenuItem).Header as String == "Share To")
                    break;
            }
            if (i < menu.Items.Count)
            {
                UElementMenuDirectory share = menu.Items[i] as UElementMenuDirectory;
                int number = int.Parse(this.Number.Substring(3));
                share.Items.RemoveAt(number);
            }
        }

        protected override bool BeforeInputReceived(UTable.Input.InputEventArgs args)
        {
            if (this.OwnerId > FingerEventArgs.PureFingerID)
            {
                if (args is MultiTouchEventArgs)
                {
                    MultiTouchEventArgs margs = args as MultiTouchEventArgs;
                    if (margs.FingerEvents.Count > 0)
                    {
                        int id = margs.FingerEvents[0].UserID;
                        if (id != OwnerId)
                        {
                            args.Handled = true;
                            args.RouteDown = false;
                            return false;
                        }
                    }
                }
            }
            
            return true;
        }

        #region Properties

        public string LibraryPath
        {
            get { return (string)GetValue(LibraryPathProperty); }
            set { SetValue(LibraryPathProperty, value); }
        }

        public static readonly DependencyProperty LibraryPathProperty =
            DependencyProperty.Register("LibraryPath", typeof(string), typeof(UWorkspace), new UIPropertyMetadata("Libraries\\TestLibrary"));


        public String Number
        {
            get { return (String)GetValue(NumberProperty); }
            set { SetValue(NumberProperty, value); }
        }

        public static readonly DependencyProperty NumberProperty =
            DependencyProperty.Register("Number", typeof(String), typeof(UWorkspace), new UIPropertyMetadata(String.Empty));

        public int WorkspaceNumber
        {
            get 
            {
                return int.Parse(Number.Substring(Number.Length - 1));
            }
            set
            {
                Number = "No. " + value;
            }
        }


        /// <summary>
        /// -1 means no owner, and anyone can manipulate the workspace
        /// >=0 means a user
        /// </summary>
        public int OwnerId = FingerEventArgs.PureFingerID;

        /// <summary>
        /// The color for drawing and messages
        /// </summary>
        public Color PenColor = UMeeting.AnonymousUserColor;


        #endregion

		public void RefreshLibrary()
		{
			String[] directories = Directory.GetDirectories(LibraryPath);
			this.DrawerGrid.Items.Clear();

			foreach (String directory in directories)
			{
				if (Directory.Exists(directory))
				{
                    WorkspaceObjectType type = GetObjectType(directory);
                    UObjectPreview preview = null;
                    if (type == WorkspaceObjectType.Book)
                    {
                        preview = new UBookPreview();
                        UBookModel model = new UBookModel();
                        model.FolderPath = directory;
                        preview.InitializeModel(model);
                    }
                    else if (type == WorkspaceObjectType.Album)
                    {
                        preview = new UAlbumPreview();
                        UAlbumModel model = new UAlbumModel(directory, AlbumBrowseMode.Scan);
                        preview.FolderPath = directory;
                        preview.InitializeModel(model);
                    }
                    if (preview != null)
                    this.DrawerGrid.Items.Add(preview);
				}
			}
        }

        #region Message Box

        public void AddMessage(String msg, Color color)
        {
            TextBlock text = new TextBlock();
            text.Text = msg;
            text.Foreground = new SolidColorBrush(color);
            text.Width = 190;
            text.FontSize = 15;
            text.TextWrapping = TextWrapping.Wrap;
            UListBoxItem item = new UListBoxItem();
            item.Content = text;
            this.MessageList.Items.Add(item);
            this.MessageList.ScrollIntoView(item);
        }

        public void ClearMessage()
        {
            this.MessageList.Items.Clear();
        }

        public void AddMessage(String msg, int userId)
        {
            if (userId < 0)
                AddMessage(msg, UMeeting.AnonymousUserColor);
            else
                AddMessage(msg, UMeeting.ColorList[userId]);
        }

        public class Message
        {
            public string Text { get; set; }
        }

        public void CheckMessageCount()
        {
            if (this.MessageList.Items.Count > 3)
            {
                int reduceCount = this.MessageList.Items.Count - 3;
                for (int i = 0; i < reduceCount; i++)
                    MessageList.Items.RemoveAt(0);
            }
        }

        #endregion


        #region Share Object

        public ReceiveSharedObjectMessage currentSharingMessage = null;

        public void OnSharingMessageReceived(ReceiveSharedObjectMessage msg)
        {
            ShowShareRequestMessage(msg);
        }

        public void ShowShareRequestMessage(ReceiveSharedObjectMessage msg)
        {
            if (currentSharingMessage != null)
                OnDiscardSharing(null, null);
            currentSharingMessage = msg;

            Color color = UMeeting.AnonymousUserColor;
            if (msg.SourceUserId >= 0)
                color = UMeeting.ColorList[msg.SourceUserId];

            Grid g = new Grid();
            g.Width = 190;
            g.Height = 44;
            g.RowDefinitions.Add(new RowDefinition());
            g.RowDefinitions.Add(new RowDefinition());
            TextBlock text = new TextBlock();
            text.Foreground = new SolidColorBrush(color);
            text.FontSize = 15;
            text.Text = "User " + msg.SourceUserId + " shares a book to you:";
            UButton acceptButton = new UButton();
            Grid.SetRow(acceptButton, 1);
            acceptButton.Width = 80;
            acceptButton.HorizontalAlignment = HorizontalAlignment.Left;
            acceptButton.Foreground = new SolidColorBrush(color);
            acceptButton.Content = "Accept";
            acceptButton.Margin = new Thickness(10, -5, 0, 0);
            acceptButton.Pressed += new ButtonEventHandler(OnAccpetSharing);

            UButton discardButton = new UButton();
            Grid.SetRow(discardButton, 1);
            discardButton.Width = 80;
            discardButton.HorizontalAlignment = HorizontalAlignment.Right;
            discardButton.Foreground = new SolidColorBrush(color);
            discardButton.Content = "Discard";
            discardButton.Margin = new Thickness(0, -5, 10, 0);
            discardButton.Pressed += new ButtonEventHandler(OnDiscardSharing);
            g.Children.Add(text);
            g.Children.Add(acceptButton);
            g.Children.Add(discardButton);
            g.Tag = msg;
            this.MessageList.Items.Add(g);
            this.MessageList.ScrollIntoView(g);
        }

        void OnAccpetSharing(object sender, ButtonEventArgs args)
        {
            if (currentSharingMessage == null)
                return;

            RemoveBook();

            // Open the book in read region
            UObject obj = OpenBookInReadRegion(currentSharingMessage.SourceObject.GetModel());

            UTableHelper.ShareCenter.AddShare(currentSharingMessage.SourceObject, obj, true);

            UMeeting.WorkspaceList[currentSharingMessage.SourceWorkspaceId].SendMessage(
                new ShowWorkspaceMessageMessage("User " + this.OwnerId + " accepted your share", this.OwnerId));

            foreach (Object o in MessageList.Items)
            {
                if (o is Grid && (o as Grid).Tag == currentSharingMessage)
                {
                    MessageList.Items.Remove(o);
                    break;
                }
            }
            currentSharingMessage = null;
        }

        void OnDiscardSharing(object sender, ButtonEventArgs args)
        {
            UMeeting.WorkspaceList[currentSharingMessage.SourceWorkspaceId].SendMessage(
                new ShowWorkspaceMessageMessage("User " + this.OwnerId + " refused your share", this.OwnerId));

            foreach (Object o in MessageList.Items)
            {
                if (o is Grid && (o as Grid).Tag == currentSharingMessage)
                {
                    MessageList.Items.Remove(o);
                    break;
                }
            }
            currentSharingMessage = null;
        }

        #endregion

        public override void OnMessageReceived(object message)
        {
            if (message is SetWorkspaceNumberMessage)
            {
                this.Number = (message as SetWorkspaceNumberMessage).Number;
                return;
            }
            else if (message is ShowWorkspaceMessageMessage)
            {
                ShowWorkspaceMessageMessage msg = message as ShowWorkspaceMessageMessage;
                this.AddMessage(msg.Message, msg.FromUserId);
            }
            else if (message is ReceiveSharedObjectMessage)
            {
                this.OnSharingMessageReceived(message as ReceiveSharedObjectMessage);
            }
            else if (message is String)
            {
                Console.WriteLine(this.Number + ": " + message);
            }
            base.OnMessageReceived(message);
        }

        public override object OnDataQuerying(object dataFlag)
        {
            if (dataFlag is QueryWorkspaceOnwerIdMessage)
                return this.OwnerId;

            return base.OnDataQuerying(dataFlag);
        }

        void ReadRegionBorder_InputReceived(UTable.Input.InputEventArgs args)
		{
			if (ReadRegion.Children.Count > 0)
			{
				args.Handled = true;
				args.RouteDown = false;
			}
		}

		void UWorkspace_Unactivated(object sender, EventArgs e)
		{
		    // Shadow.ShadowDepth = 8;
		}

		void UWorkspace_Activated(object sender, EventArgs e)
		{
			// Shadow.ShadowDepth = 6;
		}

		void DrawerGrid_ItemTapped(UGridViewPanel sender, UGridViewEventArgs args)
		{
			// UBookPreviewControl preview = args.Item.Content as UBookPreviewControl;
			// OpenBookInReadRegion(preview.PagesFolderPath);
            try
            {
                UBookPreview book_preview = args.Item.Content as UBookPreview;
                UBookModel model = book_preview.GetModel() as UBookModel;

                // Open the book in read region
                UObject obj = OpenBookInReadRegion(model);

                UTableHelper.ShareCenter.AddShare(book_preview, obj, true);
                UTableHelper.ShareCenter.RemoveShare(book_preview);

                DrawerGrid.Items.Remove(args.Item);
                DrawerGrid.Items.Remove(book_preview);
            }
            catch (System.Exception e)
            {
                ULogger.ErrorException("Exception in DrawerGrid_ItemTapped of uWorkspace", e);
            }
		}

        void UWorkspace_ChildrenChanged(IObject sender, ObjectChildrenChangedEventArgs args)
        {
            if (args.Added != null && args.Added.ObjectType.IsSubclassOf (typeof(UObjectPreview)))
            {
                args.Added.LayoutChanged += BookPreview_LayoutChanged;
                args.Added.OwnerChanged += BookPreview_OwnerChanged;
				args.Added.DragEnded += BookPreview_DragEnded;
            }
        }

		void BookPreview_DragEnded(IObject sender, ObjectDragEventArgs args)
		{
			// read the book if the book preview is located in read region
			if (CheckTargetInPlace(sender, ReadRegion))
			{
				// query the data from the sender
				object model = sender.QueryData(new QueryModelMessage());

				// Open the book in read region
                UObject obj = OpenBookInReadRegion(model);

                if (UTableHelper.ShareCenter.IsSharing(sender))
                {
                    UTableHelper.ShareCenter.AddShare(sender, obj, true);
                }
                sender.Close();
			}
			else if (CheckTargetInPlace(sender, Drawer) && Drawer.IsOpen)
			{
                UObjectPreview preview = null;
                // query the data from the sender
                object model = sender.QueryData(new QueryModelMessage());
                if (model is UBookModel)
                    preview = new UBookPreview();
                else if (preview is UAlbumPreview)
                    preview = new UAlbumPreview();
                else
                    return;
				if (UTableHelper.ShareCenter.IsSharing(sender))
				{
                    UTableHelper.ShareCenter.AddShare(sender, preview, true);
				}
				else
				{
                    preview.SendMessage(new InitializeModelMessage(model));
				}
                preview.Menu.Loaded += new RoutedEventHandler(Menu_Loaded);

				Point p = sender.TranslatePoint(new Point(0, 0), this);
				p = this.TranslatePoint(p, Drawer);
				UGridViewItem item = new UGridViewItem();
                item.Content = preview;
				Canvas.SetTop(item, p.Y);
				Canvas.SetLeft(item, p.X);
				// put the element in the drawer
				sender.Close();
				this.DrawerGrid.Items.Add(item);
			}
		}

        void BookPreview_OwnerChanged(object sender, EventArgs e)
        {
            (sender as IObject).LayoutChanged -= BookPreview_LayoutChanged;
            (sender as IObject).OwnerChanged -= BookPreview_OwnerChanged;
			(sender as IObject).DragEnded -= BookPreview_DragEnded;
        }

        void BookPreview_LayoutChanged(IObject sender, ObjectLayoutChangedEventArgs args)
        {

        }

        UObject OpenBookInReadRegion(object model)
        {
            UObject obj = null;
            if (model is UBookModel)
            {
                obj = new UBook();
                obj.SendMessage(new InitializeModelMessage(model));
                (obj as UBook).PenColor = PenColor;
                (obj as UBook).UserId = OwnerId;
            }
            else if (model is UAlbumModel)
            {
                obj = new UAlbum();
                obj.SendMessage(new InitializeModelMessage(model));
            }
            else
            {
                return obj;
            }

			// remove the book firstly
			RemoveBook();

            double book_ratio = 4.0 / 3.0;   // width/height
            Rect region_rect = new Rect(ReadRegion.TranslatePoint(new Point(0, 0), this), new Size(ReadRegion.ActualWidth, ReadRegion.ActualHeight));
            Rect book_rect = FitInRegion(region_rect, book_ratio, Dock.Bottom);
			obj.Width = book_rect.Width / 2;
            obj.Height = book_rect.Height / 2;
            obj.HorizontalAlignment = HorizontalAlignment.Left;
            obj.VerticalAlignment = VerticalAlignment.Bottom;
			// book.CanNote = false;
			obj.MenuDisplay = UObjectMenuDisplayType.Hide;
			obj.Width = book_rect.Width;
			obj.Height = book_rect.Height;
            this.ReadRegion.Children.Add(obj);
			// AnimationUtility.DoDoubleAnimation(book_rect.Width, TimeSpan.FromMilliseconds(800), FrameworkElement.WidthProperty, book);
			// AnimationUtility.DoDoubleAnimation(book_rect.Height, TimeSpan.FromMilliseconds(800), FrameworkElement.HeightProperty, book);
			RefreshControlButtons();
            return obj;
        }

        public UBook GetReadingBook()
        {
            if (this.ReadRegion.Children.Count > 0)
            {
                UBook book = this.ReadRegion.Children[0] as UBook;
                return book;
            }
            return null;
        }

		private WorkspaceObjectType GetObjectType(string folderPath)
		{
			String[] files = Directory.GetFiles(folderPath);
			List<String> fileList = new List<string>(files);
			fileList.Sort();
			foreach (String file in fileList)
			{
				if (File.Exists(file))
				{
					if (file.EndsWith("book.jpg") || file.EndsWith("book.png"))
						return WorkspaceObjectType.Book;
					else if (file.EndsWith("album.jpg") || file.EndsWith("album.png")) 
						return WorkspaceObjectType.Album;
				}
			}
			return WorkspaceObjectType.Unknown;
		}

		void RefreshControlButtons()
		{
			if (this.ReadRegion.Children.Count == 0)
			{
				NoteButton.Visibility = Visibility.Collapsed;
				ClearButton.Visibility = Visibility.Collapsed;
				PhotoBrowseButton.Visibility = Visibility.Collapsed;
				CloseButton.Visibility = Visibility.Collapsed;
                ShareButton.Visibility = Visibility.Collapsed;
			}
			else
			{
				if (this.ReadRegion.Children[0] is UBook)
				{
					NoteButton.Visibility = Visibility.Visible;
					ClearButton.Visibility = Visibility.Visible;
					PhotoBrowseButton.Visibility = Visibility.Collapsed;
					CloseButton.Visibility = Visibility.Visible;
                    ShareButton.Visibility = Visibility.Visible;
				}
				else if (this.ReadRegion.Children[0] is UAlbum)
				{
					NoteButton.Visibility = Visibility.Collapsed;
					ClearButton.Visibility = Visibility.Collapsed;
					PhotoBrowseButton.Visibility = Visibility.Visible;
					CloseButton.Visibility = Visibility.Visible;
                    ShareButton.Visibility = Visibility.Visible;
				}
			}
		}

        Rect FitInRegion(Rect region, double ratio, Dock placement)
        {
            double fit_width = region.Width;
            double fit_height = region.Height;
            if (fit_width / fit_height > ratio)
            {
                fit_width = fit_height * ratio;
            }
            else
            {
                fit_height = fit_width / ratio;
            }
            Point fit_position = new Point(); 
            switch (placement)
            {
                case Dock.Top:
                case Dock.Left:
                    fit_position = region.Location;
                    break;
                case Dock.Bottom:
                case Dock.Right:
                    fit_position = region.Location + new Vector(region.Width - fit_width, region.Height - fit_height);
                    break;
            }
            return new Rect(fit_position.X, fit_position.Y, fit_width, fit_height);
        }

		Boolean CheckTargetInPlace(IObject target, FrameworkElement place)
		{
			double height = target.Height;
			double width = target.Width;
			return IsPointInPlace(target, new Point(0, 0), place) &&
				IsPointInPlace(target, new Point(0, height), place) &&
				IsPointInPlace(target, new Point(width, 0), place) &&
				IsPointInPlace(target, new Point(width, height), place);
		}

        Boolean IsPointInPlace(IObject target, Point p, FrameworkElement place)
        {
            p = target.TranslatePoint(p, this);
            p = this.TranslatePoint(p, place);
            if (p.X > 0 && p.X < place.ActualWidth && p.Y > 0 && p.Y < place.ActualHeight)
                return true;
            else
                return false;
        }

        void DrawerGrid_ItemDropOut(UGridViewPanel sender, UGridViewEventArgs args)
        {
            UGridViewItem item = args.Item;
			UObjectPreview book_preview = item.Content as UObjectPreview;
            Image img = item.Content as Image;
            
            // create the image preview on the workspace
            ObjectCreateParameter param = new ObjectCreateParameter(book_preview.GetType());
            IObject preview = UTableHelper.CreateObject(param);
            preview.Position = item.TranslatePoint(new Point(0, 0), this);
            preview.Width = item.Width;
            preview.Height = item.Height;
            preview.Owner = this;

			UTableHelper.ShareCenter.AddShare(book_preview, preview, true);
            UTableHelper.ShareCenter.RemoveShare(book_preview);
			DrawerGrid.Items.Remove(item);
            DrawerGrid.Items.Remove(book_preview);

            //TODO: there is memory leak here
            BookPreview_LayoutChanged(preview, null);
        }

		private void NoteButton_Checked(object sender, RoutedEventArgs e)
		{
            if (this.ReadRegion.Children.Count > 0)
            {
                UBook book = this.ReadRegion.Children[0] as UBook;
                if (book != null)
                {
                    book.WorkType = UBookWorkType.Noting;
                }
            }
            ClearButton.IsChecked = false;
		}

		private void NoteButton_Unchecked(object sender, RoutedEventArgs e)
		{
            if (this.ReadRegion.Children.Count > 0)
            {
                UBook book = this.ReadRegion.Children[0] as UBook;
                if (book != null)
                {
                    book.WorkType = UBookWorkType.Reading;
                }
            }
		}

		private void ClearButton_Pressed(object sender, ButtonEventArgs args)
		{
			if (this.ReadRegion.Children.Count > 0)
			{
				UBook book = this.ReadRegion.Children[0] as UBook;
				if (book != null)
				{
					book.ClearLeftPageNote();
					book.ClearRightPageNote();
				}
			}
		}

        private void ClearButton_Checked(object sender, RoutedEventArgs e)
        {
            if (this.ReadRegion.Children.Count > 0)
            {
                UBook book = this.ReadRegion.Children[0] as UBook;
                if (book != null)
                {
                    book.WorkType = UBookWorkType.Erasering;
                }
            }
            NoteButton.IsChecked = false;
        }

        private void ClearButton_Unchecked(object sender, RoutedEventArgs e)
        {
            if (this.ReadRegion.Children.Count > 0)
            {
                UBook book = this.ReadRegion.Children[0] as UBook;
                if (book != null)
                {
                    book.WorkType = UBookWorkType.Reading;
                }
            }
        }

		public void RemoveBook()
		{
			if (this.ReadRegion.Children.Count > 0)
			{
				UObject book = this.ReadRegion.Children[0] as UObject;
				this.ReadRegion.Children.Remove(book);
				if (book != null)
				{
                    UObjectPreview book_preview = new UBookPreview();
					book_preview.FolderPath = book.QueryData(new QueryFolderPathMessage()) as String;
                    book_preview.Menu.Loaded += new RoutedEventHandler(Menu_Loaded);
                    UTableHelper.ShareCenter.AddShare(book, book_preview, true);
                    UTableHelper.ShareCenter.RemoveShare(book);
					UGridViewItem item = new UGridViewItem();
					item.Content = book_preview;
					item.Width = 100;
					item.Height = 150;
					Canvas.SetLeft(item, ReadRegion.TranslatePoint(new Point(0, 0), this).X);
					Canvas.SetTop(item, ReadRegion.TranslatePoint(new Point(0, 0), this).Y);
					this.Stage.Children.Add(item);
					Point target = Drawer.TranslatePoint(new Point(0, 0), this);
					AnimationUtility.DoDoubleAnimation(target.Y, TimeSpan.FromMilliseconds(500), Canvas.TopProperty, item);
					AnimationUtility.DoDoubleAnimation(target.X, TimeSpan.FromMilliseconds(450), Canvas.LeftProperty, item, new EventHandler(delegate(Object obj, EventArgs a)
					{
						this.Stage.Children.Remove(item);
						this.DrawerGrid.Items.Add(item);
					}));
				}
			}
		}

		private void CloseButton_Pressed(object sender, ButtonEventArgs args)
		{
			RemoveBook();
			RefreshControlButtons();
		}

        private void ShareButton_Pressed(object sender, ButtonEventArgs args)
        {
            ChooseShareTargetDialog dialog = new ChooseShareTargetDialog();
            // dialog.Closed += new UDialogClosedEventHandler(dialog_Closed);
            int id = int.Parse(this.Number.Substring(this.Number.Length - 1));
            for (int i = 0; i < UMeeting.WorkspaceList.Count; i++)
            {
                if (i != id)
                    dialog.WorkspaceList.Add("Workspace No. " + i);
            }
            dialog.TargetShareChoosed += new ChooseShareTargetDialogHandler(dialog_TargetShareChoosed);
            dialog.Open();
        }

        void dialog_TargetShareChoosed(int choosedId)
        {
            IObject target = UMeeting.WorkspaceList[choosedId];
            target.SendMessage(new ReceiveSharedObjectMessage(GetReadingBook(), OwnerId, WorkspaceNumber));
        }

		private void PhotoBrowseButton_Pressed(object sender, ButtonEventArgs args)
		{
			UAlbum album = this.ReadRegion.Children[0] as UAlbum;
			if (album != null)
			{
				if (album.BrowseMode == AlbumBrowseMode.Grid)
				{
					album.BrowseMode = AlbumBrowseMode.Scan;
					AlbumGridImage.Visibility = Visibility.Visible;
					AlbumScanImage.Visibility = Visibility.Collapsed;
				}
				else
				{
					album.BrowseMode = AlbumBrowseMode.Grid;
					AlbumGridImage.Visibility = Visibility.Collapsed;
					AlbumScanImage.Visibility = Visibility.Visible;
				}
			}
		}

        private void BindUserButton_Pressed(object sender, UTable.Objects.Controls.ButtonEventArgs args)
        {
            int id = args.UserId;
            if (id > FingerEventArgs.PureFingerID)
            {
                this.PenColor = UMeeting.GetColor(args.UserId);
                UBook book = GetReadingBook();
                if (book != null)
                {
                    book.PenColor = this.PenColor;
                    book.UserId = id;
                }

                this.BindUserButton.Visibility = Visibility.Collapsed;
                this.BindUserText.Text = "User " + id + " in ";
                this.BindUserText.Foreground = new SolidColorBrush(PenColor);
                this.BindUserText.Visibility = Visibility.Visible;
                this.UnbindUserButton.Visibility = Visibility.Visible;
                this.OwnerId = id;
                AddMessage("User " + id + " is binded to this workspace", OwnerId);
            }
        }

        private void UnbindUserButton_Pressed(object sender, ButtonEventArgs args)
        {
            this.PenColor = UMeeting.AnonymousUserColor;
            UBook book = GetReadingBook();
            if (book != null)
                book.PenColor = this.PenColor;

            this.BindUserButton.Visibility = Visibility.Visible;
            this.BindUserText.Visibility = Visibility.Collapsed;
            this.UnbindUserButton.Visibility = Visibility.Collapsed;
            this.OwnerId = FingerEventArgs.PureFingerID;
            AddMessage("No user in workspace now.", OwnerId);
        }

        #region IControlDisposable Members

        public void DisposeControl()
        {
            Console.WriteLine("Dispose Workspace");
            NoteButton.Checked -= NoteButton_Checked;
            NoteButton.Unchecked -= NoteButton_Unchecked;
            ReadToolbar.Children.Remove(NoteButton);
        }

        #endregion
    }

	public enum WorkspaceObjectType
	{
		Album,
		Book,
		Unknown,
	}

	public class SetFolderPathMessage
	{
		public SetFolderPathMessage(string path)
		{
			FolderPath = path;
		}

		public String FolderPath { get; protected set; }
	}

	public class QueryFolderPathMessage
	{

	}

    public class SetWorkspaceNumberMessage
    {
        public String Number { get; private set; }

        public SetWorkspaceNumberMessage(String number)
        {
            this.Number = number;
        }
    }

    public class QueryWorkspaceOnwerIdMessage
    {

    }
    

    public class ShowWorkspaceMessageMessage
    {
        public String Message { get; set; }

        public int FromUserId { get; set; }

        public ShowWorkspaceMessageMessage(String message, int userId)
        {
            Message = message;

            FromUserId = userId;
        }
    }

    public class ReceiveSharedObjectMessage
    {
        public UObject SourceObject { get; set; }

        public int SourceUserId { get; set; }

        public int SourceWorkspaceId { get; set; }

        public ReceiveSharedObjectMessage(UObject obj, int sharerId, int workspaceId)
        {
            SourceObject = obj;
            SourceUserId = sharerId;
            SourceWorkspaceId = workspaceId;
        }
    }

}
